package com.yl.framework.beans.factory.xml;

import com.yl.framework.beans.BeanDefinition;
import com.yl.framework.beans.MutablePropertyValues;
import com.yl.framework.beans.PropertyValue;
import com.yl.framework.beans.factory.support.BeanDefinitionReader;
import com.yl.framework.beans.factory.support.BeanDefinitionRegistry;
import com.yl.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @Author 小羊
 * @Date 2/11/2024下午 3:32
 * @ClassName XmlBeanDefinitionReader
 * @Description 针对xml配置文件进行解析的类
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {
    /**\
     * 声明注册表对象
     */
    private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
    }

    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
        this.registry = new SimpleBeanDefinitionRegistry();
    }

    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        //使用dom4j进行xml配置文件的解析
        SAXReader reader = new SAXReader();
        //获取类路径下的配置文件
        InputStream is = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);
        Document document = reader.read(is);
        //根据document对象获取根标签对象
        Element rootElement = document.getRootElement();
        //获取根标签下所有的bean标签对象
        List<Element> elements = rootElement.elements("bean");
        for (Element element : elements) {
            //获取id属性
            String id = element.attributeValue("id");
            //获取class属性
            String className = element.attributeValue("class");
            //将id和class属性封装到BeanDefinition对象
            //1、创建BeanDefinition
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);
            //创建MutablePropertyValues对象
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
            //获取bean标签下所有的property对象
            List<Element> propertyElements = element.elements("property");
            for (Element propertyElement : propertyElements) {
                String name = propertyElement.attributeValue("name");
                String ref = propertyElement.attributeValue("ref");
                String value = propertyElement.attributeValue("value");
                PropertyValue propertyValue = new PropertyValue(name,ref,value);
                mutablePropertyValues.addPropertyValue(propertyValue);
            }
            //将mutablePropertyValues封装到beanDefinition对象中
            beanDefinition.setPropertyValues(mutablePropertyValues);
            //将beanDefinition注册到注册表中
            registry.registerBeanDefinition(id,beanDefinition);
        }
    }
}
